package com.weishi.project.speedometer.domain;

import com.weishi.framework.config.BeanContext;
import com.weishi.project.speedometer.service.ISpeedometerService;
import com.weishi.project.speedometer.vo.MqttDataVo;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.util.logging.Logger;

public class MqttHeartCallBack implements MqttCallBackCommon {

    private ISpeedometerService speedometerService;

    Logger logger = Logger.getLogger("MqttHeartCallBack");

    public String topic = "heart";

    public MqttHeartCallBack(){
        this.speedometerService = BeanContext.getApplicationContext().getBean(ISpeedometerService.class);
    }

    public void connectionLost(Throwable throwable) {
        logger.info("Connection to MQTT broker lost!");
    }

    public void messageArrived(String s, MqttMessage mqttMessage){
        String message = new String(mqttMessage.getPayload());
        try {
            String[] datas = message.split(":");
            MqttDataVo vo = new MqttDataVo();
            vo.setType(topic);
            vo.setDevId(datas[0]);
            vo.setTimeTimp(datas[1]);
            vo.setDatas(datas);
            speedometerService.addRealTimeData(vo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
    }

    @Override
    public String getTopic() {
        return topic;
    }
}
